package com.haotunet.app.goldtreasure.net;

import android.content.Context;
import android.util.Log;

import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

@SuppressWarnings("deprecation")
public class NetUtil {

    private HttpClient mHttpClient;
    private ShareStore shareStore;

    public NetUtil(Context context) {
        mHttpClient = getHttpClient();
        shareStore = new ShareStore(context);
    }

    public String executePost(String url, HashMap<String, String> data) {

        String result = null;
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : data.keySet()) {
            params.add(new BasicNameValuePair(key, data.get(key)));
        }
        try {
            HttpPost request = new HttpPost(url);
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            request.addHeader("Authorization", "Bearer " + shareStore.getString(Strs.TOKEN, ""));
            request.addHeader("_version", shareStore.getString("versionName", ""));
            request.addHeader("_platform", "android");
            request.addHeader("Referer", "api.goldplusgold.com");
            HttpResponse response = mHttpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();

            if (HttpStatus.SC_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                saveToken(response);
                if (null != entity) {
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    entity.consumeContent();
                }

            } else {

                request.abort();
                System.out.println(url + " code:" + statusCode + " ERROR!");
            }
        } catch (IOException e) {

            System.out.println(url + " ERROR! " + e.getMessage());
        }

        return result;
    }

    public String executePut(String url, HashMap<String, String> data) {

        String result = null;
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : data.keySet()) {
            params.add(new BasicNameValuePair(key, data.get(key)));
        }

        try {
            HttpPut request = new HttpPut(url);
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            request.addHeader("Authorization", "Bearer " + shareStore.getString(Strs.TOKEN, ""));
            request.addHeader("_version", shareStore.getString("versionName", ""));
            request.addHeader("_platform", "android");
            request.addHeader("Referer", "api.goldplusgold.com");
            Log.i("******************* ", shareStore.getString(Strs.TOKEN, ""));
            HttpResponse response = mHttpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();

            if (HttpStatus.SC_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                saveToken(response);
                if (null != entity) {
                    result = EntityUtils.toString(entity, HTTP.UTF_8);

                    entity.consumeContent();
                }
            } else {
                request.abort();
                System.out.println(url + " code:" + statusCode + " ERROR!");
            }
        } catch (IOException e) {

            System.out.println(url + " ERROR! " + e.getMessage());
        }

        return result;

    }

    public String executeDelete(String url, HashMap<String, Object> data) {

        String result = null;
        String paramStr = "";
        if (data != null) {

            Iterator<Entry<String, Object>> iter = data.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Object> entry = iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                paramStr += paramStr = "&" + key + "=" + val;
            }
            if (!paramStr.equals("")) {
                paramStr = paramStr.replaceFirst("&", "?");
                url += paramStr;
            }
            System.out.println(url);
        }

        try {
            HttpDelete delete = new HttpDelete(url);
            delete.addHeader("Authorization", "Bearer " + shareStore.getString(Strs.TOKEN, ""));
            delete.addHeader("_version", shareStore.getString("versionName", ""));
            delete.addHeader("_platform", "android");
            delete.addHeader("Referer", "api.goldplusgold.com");
            HttpResponse response = mHttpClient.execute(delete);
            int statusCode = response.getStatusLine().getStatusCode();
            Log.i("*******************", statusCode + "");
            if (HttpStatus.SC_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    entity.consumeContent();
                }

            } else {

                delete.abort();
                System.out.println(url + " code:" + statusCode + " ERROR!");
            }
        } catch (IOException e) {

            System.out.println(url + " ERROR! " + e.getMessage());
        }

        return result;

    }

    public String executeGet(String url, HashMap<String, Object> params) {
        String result = null;
        String paramStr = "";
        if (params != null) {

            Iterator<Entry<String, Object>> iter = params.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Object> entry = iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                paramStr += paramStr = "&" + key + "=" + val;
            }
            if (!paramStr.equals("")) {
                paramStr = paramStr.replaceFirst("&", "?");
                url += paramStr;
            }
            System.out.println(url);
        }
        try {
            HttpGet request = new HttpGet(url);
            request.addHeader("Authorization", "Bearer " + shareStore.getString(Strs.TOKEN, ""));
            request.addHeader("_platform", "android");
            request.addHeader("_version", shareStore.getString("versionName", ""));
            request.addHeader("Referer", "api.goldplusgold.com");
            HttpResponse response = mHttpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            Log.i("*******************", statusCode + "");
            if (HttpStatus.SC_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                saveToken(response);
                if (null != entity) {
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    entity.consumeContent();
                }

            } else {

                request.abort();
                System.out.println(url + " code:" + statusCode + " ERROR!");
            }
        } catch (IOException e) {

            System.out.println(url + " ERROR! " + e.getMessage());
        }

        return result;
    }

    public String getRedirectInfo(String url, HashMap<String, String> data) {
        String result = null;
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : data.keySet()) {
            params.add(new BasicNameValuePair(key, data.get(key)));
        }
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext httpContext = new BasicHttpContext();
        try {
            HttpPost request = new HttpPost(url);
            // StringEntity sEntity = new StringEntity(str, HTTP.UTF_8);
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            request.addHeader("Authorization", "Bearer " + shareStore.getString(Strs.TOKEN, ""));
            request.addHeader("_version", shareStore.getString("versionName", ""));
            request.addHeader("_platform", "android");
            request.addHeader("Referer", "api.goldplusgold.com");
            // 将HttpContext对象作为参数传给execute()方法,则HttpClient会把请求响应交互过程中的状态信息存储在HttpContext中
            HttpResponse response = httpClient.execute(request, httpContext);
            // 获取重定向之后的主机地址信息"
            HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            // 获取实际的请求对象的URI,即重定向之后的"login"
            HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
            System.out.println("主机地址:" + targetHost.toString());
            System.out.println("主机地址:" + targetHost);
            System.out.println("URI信息:" + realRequest.getURI());
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                saveToken(response);
                result = EntityUtils.toString(entity, HTTP.UTF_8);
                entity.consumeContent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }

    private void saveToken(HttpResponse response) {

        Header[] headers = response.getAllHeaders();
        if (headers != null) {
            for (int i = 0; i < headers.length; i++) {
                if ("_x-access-token".equals(headers[i].getName())) {
                    shareStore.putString(Strs.TOKEN, headers[i].getValue());
                    shareStore.commit();
                }
            }
        }
    }

    private HttpClient getHttpClient() {
        BasicHttpParams params = new BasicHttpParams();
        HttpConnectionParams.setStaleCheckingEnabled(params, true);
        HttpConnectionParams.setConnectionTimeout(params, 115000);
        HttpConnectionParams.setSoTimeout(params, 115000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);
        HttpClientParams.setRedirecting(params, false);
        SSLSocketFactory sf;
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sf = new SSLSocketFactoryImp(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            return new DefaultHttpClient(params);
        }

        ConnPerRouteBean connPerRouteBean = new ConnPerRouteBean(20);
        connPerRouteBean.setDefaultMaxPerRoute(20);
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRouteBean);
        ConnManagerParams.setTimeout(params, 115000);
        ConnManagerParams.setMaxTotalConnections(params, 1000);

        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/Android");
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sf, 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

        return new DefaultHttpClient(cm, params);
    }

}
